package com.luolc.syllabustest;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.luolc.syllabustest.widget.SyllabusClassTimeInfoView;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Name:编辑课程表
 * Author: WK（wangkun@xjzhicheng.com)
 * Date: 2016-10-11
 * <br><b>
 * Describe: 编辑课程表的课程页面<br>
 * 1.编辑课程名称<br>
 * 2.编辑课程讲师<br>
 * 3.编辑上课时段（可添加多个时段）<br>
 * <br><b>Tip:
 * 1.周数不能重复，（周数重复，节课不能重复）
 */
public class CreateCoursePage extends AppCompatActivity {

    public static final int ID_BEGIN = 1000;//自定义ID

    @Bind(R.id.ll_content_root)
    LinearLayout mLlContentRoot;//内容RootView
    @Bind(R.id.ll_add_class_time_root)
    LinearLayout mLlAddClassTimeRoot;//添加Class时间的位置
    @Bind(R.id.ll_add_class_time_bar)
    LinearLayout mLlAddClassTimeBar;//Add View操作条
    @Bind(R.id.tv_class_name)
    EditText mTvClassName;
    @Bind(R.id.tv_class_teacher)
    EditText mTvClassTeacher;

    private int viewID = ID_BEGIN;
    private int viewContainerBeginPosition = 0;//视图容器开始位置

    private ArrayList<SyllabusClassTimeInfoView> viewContainer = new ArrayList<>();//视图容器


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_course);
        ButterKnife.bind(this);
        initView();
        setUpListener();
    }

    @SuppressWarnings("ResourceType")
    private void initView() {
        addClassTimeView();
        showAddBar();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.create_course, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.submit:
                //TODO 提交课程
                if (isHasClassName()) {
                    if (isWeekConflictPass) {
                        if (isHasClassTimePass) {
                            if (isClassTimeConflictPass) {
                                Toast.makeText(this, "已提交，服务器", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(this, "课程有冲突，请检查课程周，星期，课节是否有冲突", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(this, "请点击选择课程时间", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(this, "请点击选择单，双，混周", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(this, "请填写课程名称", Toast.LENGTH_SHORT).show();
                }
                break;
        }
        return true;
    }


    private void setUpListener() {
        mLlAddClassTimeBar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addClassTimeView();
            }
        });
    }

    /**
     * 课程名称验证
     *
     * @return true 通过不为空验证
     */
    boolean isHasClassName() {
        if (!TextUtils.isEmpty(mTvClassName.getText())) {
            return true;
        }
        return false;
    }


    boolean isWeekConflictPass;//周验证通过
    boolean isClassTimeConflictPass;// 上课时间验证通过
    boolean isHasClassTimePass;// 上课时间验证通过

    /**
     * 周数冲突
     *
     * @param inWeekData 当前要验证的数据
     * @return true 验证通过
     */
    void checkTimeConflict(View currentView, ArrayList<String> inWeekData, ArrayList<Integer> inClassTimeData) {
        int containerSize = viewContainer.size();
        if (containerSize == 1) {
            if (inWeekData.size() == 0) {
                isWeekConflictPass = false;
            } else {
                if (inClassTimeData.size() == 0) {
                    isClassTimeConflictPass = false;
                } else {
                    isClassTimeConflictPass = true;
                }
                isClassTimeConflictPass = true;
            }
        }
        for (SyllabusClassTimeInfoView item : viewContainer) {
            if (item == currentView) continue;
            if (item.getWeekData() != null) {
                ArrayList<String> localData = (ArrayList<String>) item.getWeekData().clone();
                localData.retainAll(inWeekData);
                if (localData.size() != 0) {
                    // 在交集中判断课节时间是否有冲突
                    ArrayList<Integer> localData4Class = item.getClassTimeData();
                    if (localData4Class.size() == 0) {
                        isHasClassTimePass = false;
                        isClassTimeConflictPass = false;
                        break;
                    } else {
                        isHasClassTimePass = true;
                    }
                    // 星期相同再检查
                    if (localData4Class.get(0) == inClassTimeData.get(0)) {
                        // 开始节数和结束节数的判断
                        if (localData4Class.get(2) < inClassTimeData.get(1) || localData4Class.get(1) > inClassTimeData.get(2)) {
                            isWeekConflictPass = true;
                            isClassTimeConflictPass = true;
                        } else {
                            isWeekConflictPass = true;
                            isClassTimeConflictPass = false;
                            Toast.makeText(this, "课程时间有冲突！！", Toast.LENGTH_SHORT).show();
                            break;
                        }
                    } else {
                        // 不同星期通过
                        isWeekConflictPass = true;
                        isClassTimeConflictPass = true;

                    }

                } else {
                    isWeekConflictPass = true;
                    isClassTimeConflictPass = true;
                    isHasClassTimePass = true;
                }

            } else {
                isWeekConflictPass = false;
                isClassTimeConflictPass = false;
                Toast.makeText(this, "请选择单，双，混周..", Toast.LENGTH_SHORT).show();
                break;
            }
        }

    }

    void checkClassTimeConflict(ArrayList<Integer> data) {

    }

    private void showAddBar() {
        //显示添加条
        mLlAddClassTimeBar.setVisibility(View.VISIBLE);
    }

    @SuppressWarnings("ResourceType")
    private void addClassTimeView() {
        SyllabusClassTimeInfoView initOne = new SyllabusClassTimeInfoView(this);
        initOne.setId(viewID);
        initOne.setLayoutParams(getLayoutParams());
        initOne.setRemoveClassTimeItemListener(new SyllabusClassTimeInfoView.IRemoveClassTimeItemListener() {
            //View为Himself
            @Override
            public void onClick(View view) {
                SyllabusClassTimeInfoView itSelf = (SyllabusClassTimeInfoView) view;
                //删除View
                mLlAddClassTimeRoot.removeView(view);
                //删除容器缓存
                viewContainer.remove(itSelf.getPosition() - 1);
                //更新时间Title
                updateClassTimeTitle(itSelf.getPosition() - 1);

            }
        });
        initOne.setClassTimeConflictCheck(new SyllabusClassTimeInfoView.ITimeConflictCheckListener() {

            @Override
            public void onCheck(View view, ArrayList<String> weekData, ArrayList<Integer> classTimeData) {
                //TODO 要去做Week,ClassTimeConflict验证..
                checkTimeConflict(view, weekData, classTimeData);
            }
        });
        mLlAddClassTimeRoot.addView(initOne);
        viewContainer.add(initOne);
        //设置位置 ex:"上课时间‘1‘"
        initOne.setPosition(viewContainerBeginPosition + 1);
        //自增
        viewID++;
        viewContainerBeginPosition++;
        //默认 全周，所以通过
//        isWeekConflictPass = true;
    }

    private LinearLayout.LayoutParams getLayoutParams() {
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        return layoutParams;
    }

    /**
     * 修改时间段Title
     *
     * @param currentPosition 当前删除位置
     */
    private void updateClassTimeTitle(int currentPosition) {
        //ID起点也自减
        viewContainerBeginPosition--;
        //1.选择排序
        int size = viewContainer.size();
        for (int i = currentPosition; i < size; i++) {
            SyllabusClassTimeInfoView item = viewContainer.get(i);
            item.setPosition(i + 1);
        }
        //2.重新排序
//        int size = viewContainer.size();
//        for (int i = 0; i < size; i++) {
//            SyllabusClassTimeInfoView item = viewContainer.get(i);
//            item.setPosition(i + 1);
//        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }


}
